/**
 * 
 */
package org.heydr.common;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;

import org.heydr.annotation.HandleInfo;
import org.heydr.common.filter.Filter;
import org.heydr.common.http.StringUtils;
import org.heydr.concurrent.CrawlerEngine;
import org.heydr.data.ResourceEngine;
import org.heydr.entity.Site;
import org.heydr.entity.Url;
import org.heydr.handler.HeyDrHandler;
import org.heydr.handler.impl.SubHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TaskEngine{
	private static Logger logger = LoggerFactory.getLogger(TaskEngine.class);
	
	/* task queue */
	private static LinkedBlockingDeque<Url> taskQueue = new LinkedBlockingDeque<Url>();
	/* handler map */
	private static Map<String,HeyDrHandler> handlerChainMap = new ConcurrentHashMap<String,HeyDrHandler>();
	private static ResourceEngine resourcEngine;
	private static long frequency;
	private static Long clock;
	private static Filter filter = null;
	
	private static Map<String,Site> sites;
	
	private static List<Url> finishedTasks = new ArrayList<Url>();
	
	/**
	 * <strong>Description</strong>:alarm the cylinder to refresh the ${tag}queue
	 * @param frequency
	 * @return void
	 * @author carlos.xie
	 * assist by dong
	 * 2013-5-21
	 */
	public static synchronized void emptyAlarm(){
		refresh(frequency);
	}

	/**
	 * <strong>Description</strong>:init handler chains,which have same group will be linked by increasing step counting
	 * eg:handlers both group name are "test" and step counting are 1 and 2,the second step handler is the next node of the first step handler.
	 * @param handlers
	 * @return void
	 * @author chok
	 * 2014-3-1
	 */
	public static void initHandler(Map<String,SubHandler> handlers){
		Map<String,LinkedList<SubHandler>> temp = new HashMap<String,LinkedList<SubHandler>>();
		for(Entry<String,SubHandler> entry : handlers.entrySet()){
			SubHandler handler = entry.getValue();
			String group = handler.getClass().getAnnotation(HandleInfo.class).group();
			if(!temp.containsKey(group)){
				temp.put(group, new LinkedList<SubHandler>());
			}
			temp.get(group).add(handler);
		}
		
		for(Entry<String,LinkedList<SubHandler>> entry : temp.entrySet()){
			LinkedList<SubHandler> list = entry.getValue();
			Collections.sort(list,new HandlerChainComparator());
			SubHandler handler = list.pollLast();
			while(!list.isEmpty()){
				SubHandler preHandler = list.pollLast();
				preHandler.setNextHandler(handler);
				handler = preHandler;
			}
			
			handlerChainMap.put(entry.getKey(), handler);
		}
		
	}
	
	public static void initFilter(Filter filter){
		
		TaskEngine.filter = filter;
	}
	
	public static void refreshSites(){
		if(null==sites)
			sites = new HashMap<String, Site>();
		List<Site> siteList = resourcEngine.availableSites();
		if(null != siteList && siteList.size()>0){
			for(Site site : siteList){
				sites.put(site.getSite(), site);
				Url url = new Url();
				url.setUrl(site.getEntryUrl());
				url.setUrlMd5(StringUtils.md5(url.getUrl()));
				url.setSite(site.getSite());
				url.setSiteName(site.getName());
				url.setHandleTag(site.getName());
				taskQueue.add(url);
				
				logger.info("init site:"+site.getSite());
			}
		}
	}
	
	public static Site getSite(String site){
		return sites.get(site);
	}
	
	public static void finishTask(Url url){
		if(null == finishedTasks)
			finishedTasks = new ArrayList<Url>();
		finishedTasks.add(url);
	}
	
	/**
	 * <strong>Description</strong>:refresh the queue by the tag name
	 * @param frequency
	 * @return void
	 * @author carlos.xie
	 * 2013-5-22
	 */
	private static void refresh(Long frequency){
		
		resourcEngine.finishedTasks(finishedTasks);
		finishedTasks.clear();
		
		Long now = Calendar.getInstance().getTimeInMillis();
		if(clock == null)
			//first time to refresh the queue,add the queue into the cylindricalMap,and make the timestamp as current time
			clock = now;
		
		if(now>=clock){
//			logger.info(frequency+"  feed me more!"+now);
			//already out of one cycle time,refresh the queue and mark down the current timestamp,let it jump into a new cycle.
			taskQueue.addAll(resourcEngine.availableUrls(CrawlerEngine.getConfig().getDbLimit()));
			clock += frequency;
		}else{
			logger.info("not the right time!now:"+now+" and right time is:"+clock);
		}
	}
	
	public static void setResourceEngine(ResourceEngine resourcEngine) {
		TaskEngine.resourcEngine = resourcEngine;
	}
	
	public static LinkedBlockingDeque<Url> getTaskQueue() {
		return taskQueue;
	}

	public static void setTaskQueue(LinkedBlockingDeque<Url> taskQueue) {
		TaskEngine.taskQueue = taskQueue;
	}

	public static long getFrequency() {
		return frequency;
	}
	
	public static void newTask(Url url){
		if(!alreadySnatched(url.getUrl())){
			TaskEngine.taskQueue.add(url);
		}
	}

	public static void setFrequency(long frequency) {
		TaskEngine.frequency = frequency;
	}

	public static boolean alreadySnatched(String url){
		return filter.contains(url);
	}
	
	public static void addSnatchedUrl(String url){
		filter.add(url);
	}
	
	public static synchronized HeyDrHandler matchHandlerChain(String handlerTag){
		return handlerChainMap.get(handlerTag);
	}
	
	public static void addToHandlerChainMap(String key,HeyDrHandler handler){
		handlerChainMap.put(key, handler);
	}

}
